import { createStore } from 'vuex'
import type { ActionContext } from 'vuex/types/index.js'

export interface State {
    avatarUrl: '',
    username: '',
    id: 0,   // 新增用户ID
    email: '',
    followers: 0,
    attentions: 0
}


const store = createStore({
  state: {
    avatarUrl: '',
    username: '',
    id: 0,   // 新增用户ID
    email: '',
    followers: 0,
    attentions: 0
  },
  mutations: {
    setUserInfo(state: State, payload: State) {
      state.avatarUrl = payload.avatarUrl
      state.username = payload.username
      state.id = payload.id   // 同步userId
      state.email = payload.email
      state.followers = payload.followers
      state.attentions = payload.attentions
    },
    logout(state: State) {
      state.avatarUrl = ''
      state.username = ''
      state.id = 0   // 清空userId
      state.email = ''
      state.followers = 0
      state.attentions = 0
    }
  },
  actions: {
    updateUserInfo({ commit }: ActionContext<State, State>, userInfo: State) {
      commit('setUserInfo', userInfo)
    },

    loadUserInfoFromLocalStorage({ commit }: ActionContext<State, State>) {
      // 从 localStorage 中加载用户信息
      console.log('从本地仓库加载用户信息')
      const userInfoStr = localStorage.getItem('userInfo')
      if (userInfoStr) {
        console.log('从本地仓库加载用户信息成功')
        console.log(userInfoStr);
        
        const userInfo = JSON.parse(userInfoStr)
        commit('setUserInfo', userInfo)
      }
    },
    logout({ commit }: ActionContext<State, State>) {
      commit('logout')
    }
  },
  getters: {
    getAvatar(state: State) {
      return state.avatarUrl
    },
    getUsername(state: State) {
      return state.username
    },
    getUserId(state: State) {
      return state.id
    },
    getEmail(state: State) {
      return state.email
    },
    getFollowers(state: State) {
      return state.followers
    },
    getAttentions(state: State) {
      return state.attentions
    }
  }
})

export default store